package com.cqh.recruit.interceptor;



import com.cqh.recruit.pojo.entity.Employee;
import com.cqh.recruit.pojo.entity.Student;
import com.cqh.recruit.utils.EmployeeThreadLocal;
import com.cqh.recruit.utils.JwtUtils;
import com.cqh.recruit.utils.StudentThreadLocal;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 令牌校验的拦截器
 */

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 获取到请求路径
        String requestURI = request.getRequestURI(); // 例如：/employee/login

        ////2. 判断是否是登录请求、静态资源或Swagger相关请求, 如果是则放行
        if (requestURI.contains("/api/student/stuLogin/login") || 
            requestURI.contains("/api/school/empLogin/login") ||
            requestURI.startsWith("/swagger-ui") ||
            requestURI.startsWith("/images/") ||              // 图片访问路径
            requestURI.startsWith("/v3/api-docs") ||
            requestURI.startsWith("/swagger-resources")) {
            return true;
        }

        //3. 获取请求头中的token
        String token = request.getHeader("token");

        //4. 判断token是否存在, 如果不存在, 说明用户没有登录, 返回错误信息(响应401状态码)
        if (token == null || token.isEmpty()){

            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //5. 如果token存在, 校验令牌, 如果校验失败 -> 返回错误信息(响应401状态码)
        try {
            Claims claims = JwtUtils.parseToken(token);

            // 根据请求路径判断是学生端还是学校端的请求
            if (requestURI.startsWith("/api/student")) {
                // 学生端请求，从JWT中提取学生信息并存储到ThreadLocal中
                Student student = new Student();
                student.setId(((Integer) claims.get("stuId")).longValue());
                student.setAccount((String) claims.get("account"));
                student.setName((String) claims.get("name"));

                // 将学生信息存储到ThreadLocal中
                StudentThreadLocal.set(student);
            } else if (requestURI.startsWith("/api/school")) {
                // 学校端请求，从JWT中提取员工信息并存储到ThreadLocal中
                Employee employee = new Employee();
                employee.setId(((Integer) claims.get("empId")).longValue());
                employee.setAccount((String) claims.get("account"));
                employee.setName((String) claims.get("name"));

                // 将员工信息存储到ThreadLocal中
                EmployeeThreadLocal.set(employee);
            }
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //6. 校验通过, 放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求完成后清理ThreadLocal中的数据，防止内存泄漏
        // 根据请求路径判断是学生端还是学校端的请求，清理对应ThreadLocal
        String requestURI = request.getRequestURI();
        if (requestURI.startsWith("/api/student")) {
            StudentThreadLocal.remove();
        } else if (requestURI.startsWith("/api/school")) {
            EmployeeThreadLocal.remove();
        }
    }
}